import request from "@/utils/request"
import jwtDecode from "jwt-decode"
import {
  getToken,
  setToken,
  removeToken,
  getRefreshToken,
  setRefreshToken,
} from "@/utils/auth"
import router, { resetRouter } from "@/router"
import { Message } from "element-ui"

const state = {
  token: getToken(),
  refreshToken: getRefreshToken(),
  name: "",
  avatar: "",
  introduction: "",
  roles: [],
  editStatus: {},
  // 快捷入口
  routeList: [
    { title: "options1", value: "" },
    { title: "options2", value: "" },
    { title: "options3", value: "" },
    { title: "options4", value: "" },
    { title: "options5", value: "" },
    { title: "options6", value: "" },
    { title: "options7", value: "" },
  ],
  // 报警消息默认值
  selectValue: 0,
  // 重置
  changeValue: 0,
  // 表单是否有值
  formValue: {},
  // 搜索框部门改变
  departmentValue: '',
  // 是否进入实时定位页面
  pageData: { pageIndex: 1, pageSize: 10, orderBy: 'createdTime', orderByAscent: false },
  // 考勤统计时间
  attendanceDate: {
    EnterTimeStart: null,
    EnterTimeEnd: null,
    status: false
  }
}

const mutations = {
  SET_EDITSTATUS: (state, value) => {
    state.editStatus = value
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_REFRESHTOKEN: (state, refreshToken) => {
    state.refreshToken = refreshToken
  },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  },
  SET_ROUTER: (state, routeArray) => {
    state.routeList = routeArray
  },
  SET_SELECTVALUE: (state, selectValue) => {
    state.selectValue = selectValue
  },
  SET_CHANGEVALUE: (state, changeValue) => {
    state.changeValue = changeValue
  },
  SET_FORMVALUE: (state, formValue) => {
    state.formValue = formValue
  },
  SET_PAGEDATA: (state, pageData) => {
    state.pageData.pageIndex = pageData.pageIndex
    state.pageData.pageSize = pageData.pageSize
  },
  SET_DEPARTMENTVALUE: (state, departmentValue) => {
    state.departmentValue = departmentValue
  },
  SET_ATTENDANCEDATE: (state, attendanceDate) => {
    state.attendanceDate = attendanceDate
  }
}

const actions = {
  // 部门改变，修改职位用到
  setAttendanceDate({ commit }, data) {
    return new Promise((resolve, reject) => {
      commit("SET_ATTENDANCEDATE", data)
      resolve()
    })
  },
  // 部门改变，修改职位用到
  setDepartmentValue({ commit }, data) {
    return new Promise((resolve, reject) => {
      commit("SET_DEPARTMENTVALUE", data)
      resolve()
    })
  },
  // 进出实时定位页面
  setPageData({ commit }, data) {
    return new Promise((resolve, reject) => {
      commit("SET_PAGEDATA", data)
      resolve()
    })
  },
  // 表单的值
  setFormValue({ commit }, data) {
    return new Promise((resolve, reject) => {
      commit("SET_FORMVALUE", data)
      resolve()
    })
  },
  // 重置表单
  setChangeValue({ commit, state }) {
    return new Promise((resolve, reject) => {
      let data = state.changeValue + 1
      commit("SET_CHANGEVALUE", data)
      resolve()
    })
  },
  // 设置报警消息默认值
  setDefult({ commit }, data) {
    return new Promise((resolve, reject) => {
      commit("SET_SELECTVALUE", data)
      resolve()
    })
  },
  // 设置快捷菜单
  quickMenu({ commit }, data) {
    return new Promise((resolve, reject) => {
      commit("SET_ROUTER", data)
      resolve()
    })
  },
  // user login
  login({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      commit("SET_TOKEN", userInfo.token)
      commit("SET_REFRESHTOKEN", userInfo.refresh_token)
      setToken(userInfo.token)
      setRefreshToken(userInfo.refresh_token)
      resolve()
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      const { user } = jwtDecode(getToken())

      if (!user) {
        reject("Verification failed, please Login again.")
      }

      if (!user.IsAdmin) {
        user.roles = ["admin"]
      }

      const { roles, first_name, user_id } = user

      // roles must be a non-empty array
      if (!roles || roles.length <= 0) {
        reject("getInfo: roles must be a non-null array!")
      }

      commit("SET_ROLES", roles)
      commit("SET_NAME", first_name)
      commit("SET_AVATAR", "https://cn.vuejs.org/images/logo.png")
      commit("SET_INTRODUCTION", user_id)
      resolve(user)
    })
  },
  setEdit({ commit }, data) {
    return new Promise((resolve, reject) => {
      commit("SET_EDITSTATUS", data)
      resolve()
    })
  },
  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      commit("SET_TOKEN", "")
      commit("SET_REFRESHTOKEN", "")
      commit("SET_ROLES", [])
      commit("SET_ROUTER", [
        { title: "options1", value: "" },
        { title: "options2", value: "" },
        { title: "options3", value: "" },
        { title: "options4", value: "" },
        { title: "options5", value: "" },
        { title: "options6", value: "" },
        { title: "options7", value: "" },
      ])
      removeToken()
      resetRouter()

      // reset visited views and cached views
      // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
      dispatch("tagsView/delAllViews", null, { root: true })

      resolve()
    })
  },

  resetToken({ commit, state }, data) {
    return new Promise((resolve) => {
      commit("SET_TOKEN", data.token)
      commit("SET_REFRESHTOKEN", data.refresh_token)
      setToken(data.token)
      setRefreshToken(data.refresh_token)
      resolve()
    })
  },

  // remove token
  removeToken({ commit }) {
    return new Promise((resolve) => {
      commit("SET_TOKEN", "")
      commit("SET_ROLES", [])
      commit("SET_REFRESHTOKEN", "")
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  changeRoles({ commit, dispatch }, role) {
    return new Promise(async (resolve) => {
      const token = role + "-token"

      commit("SET_TOKEN", token)
      setToken(token)

      const { roles } = await dispatch("getInfo")

      resetRouter()

      // generate accessible routes map based on roles
      const accessRoutes = await dispatch("permission/generateRoutes", roles, {
        root: true,
      })

      // dynamically add accessible routes
      router.addRoutes(accessRoutes)

      // reset visited views and cached views
      dispatch("tagsView/delAllViews", null, { root: true })

      resolve()
    })
  },
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
}
